package apps.sim.action.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import apps.sim.Index;
import apps.sim.core.AExtendedHandler;
import apps.sim.util.ContentTypes;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

public class FileShareHandler extends AExtendedHandler {

	private FileShareHandlerConfig config = new FileShareHandlerConfig();
	private String contentType = null;

	@Override
	public void handleResponse(HttpExchange exchange, String context) throws Exception {
		final File folder = config.getFile();
		if (folder == null || !folder.exists()) {
			throw new Exception("Please configure a file to share via <img src=\"" + Index.getCurrentAddress() + "/simulate/global/src?src=http/img/settings.png\"/> icon");
		}
		final String absolutePath = folder.getAbsolutePath();
		if (folder != null && folder.exists()) {
			String extn = "";
			if (absolutePath.contains(".")) {
				extn = absolutePath.substring(absolutePath.lastIndexOf("."));
				contentType = ContentTypes.getContentType(extn);
			}
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", contentType);
			exchange.sendResponseHeaders(200, 0);
			final OutputStream responseBody = exchange.getResponseBody();
			FileInputStream in = null;
			try {
				in = new FileInputStream(folder);
				int i = 0;
				while ((i = in.read()) != -1) {
					responseBody.write(i);
				}
			} finally {
				if (in != null) {
					in.close();
				}
			}
			responseBody.flush();
			responseBody.close();
		}
	}

	@Override
	public String getDescription() {
		return "Share a over HTTP file using this. Other formats will be supported later";
	}

	public static class FileShareHandlerConfig implements IHandlerConfig {
		private File file;

		public File getFile() {
			return file;
		}

		@Config(descrition = "Configure the file to share")
		public void setFile(File folder) {
			this.file = folder;
		}

		@Override
		public String asString() {
			return file != null ? file.getAbsolutePath() : null;
		}

		@Override
		public void fromString(String string) {
			if (string != null && !string.equalsIgnoreCase("null")) {
				file = new File(string);
			}
		}

		@Override
		public IHandlerConfig cloneInstance() {
			final FileShareHandlerConfig config = new FileShareHandlerConfig();
			config.setFile(this.getFile());
			return config;
		}

	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public IHandlerConfig getHandlerConfiguration() {
		return config;
	}

	@Override
	public void setHandlerConfiguration(IHandlerConfig config) {
		this.config = (FileShareHandlerConfig) config;
	}

}
